package com.lc.zpyh.ui.activity.mine;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lc.zpyh.R;
import com.lc.zpyh.app.AppActivity;
import com.lc.zpyh.bean.Browseentity;
import com.lc.zpyh.bean.TmExcpNewVo;
import com.lc.zpyh.http.glide.GlideApp;
import com.lc.zpyh.http.request.SelectByCommodityIdApi;
import com.lc.zpyh.http.response.SelectByCommodityIdBean;
import com.lc.zpyh.other.IntentKey;
import com.lc.zpyh.sqlite.BrowseDao;
import com.lc.zpyh.ui.activity.supermarket.BusinessActivity;
import com.lc.zpyh.util.SPUtil;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;

public class FootPrintActivity extends AppActivity {
    @BindView(R.id.rv_order_goods)
    RecyclerView rvOrderGoods;
    @BindView(R.id.rl_title_bar)
    TitleBar rlTitleBar;
    private BaseQuickAdapter<TmExcpNewVo, BaseViewHolder> adapter;

    private BrowseDao browseDao;
    private static final String TAG = "FootPrintActivity";
    private List<Browseentity> listbrow = new ArrayList<>();
    private List<TmExcpNewVo> tmpList = new ArrayList<TmExcpNewVo>();
    ;
    private List<TmExcpNewVo> tmpListnew = new ArrayList<TmExcpNewVo>();
    ;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_footprint;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        browseDao = new BrowseDao(this);
        listbrow = browseDao.findAll();

        for (int i = 0; i < listbrow.size(); i++) {
            Log.e(TAG, "onCreate: " + listbrow.get(i).getDate());
        }
        Map<String, List<Browseentity>> resultMap = new HashMap<String, List<Browseentity>>();

        try {
            for (int i = 0; i < listbrow.size(); i++) {
                Browseentity dataBean = listbrow.get(i);
                String key = dataBean.getDate();

                if (resultMap.containsKey(key)) {//map中异常批次已存在，将该数据存放到同一个key（key存放的是异常批次）的map中
                    List<Browseentity> list = resultMap.get(key);
                    list.add(dataBean);
                    resultMap.put(key, list);

                } else {//map中不存在，新建key，用来存放数据
                    List<Browseentity> list = new ArrayList<>();
                    list.add(dataBean);
                    resultMap.put(key, list);
                }
            }


        } catch (Exception e) {
//            throw new Exception("按照异常批次号对已开单数据进行分组时出现异常", e);
        }
        //最终数据
        List<TmExcpNewVo> list = new ArrayList<>();
        List<TmExcpNewVo> listnew = new ArrayList<>();
        if (!resultMap.isEmpty()) {
            // 1. entrySet遍历，在键和值都需要时使用（最常用）
            for (Map.Entry<String, List<Browseentity>> entry : resultMap.entrySet()) {
                TmExcpNewVo bean = new TmExcpNewVo();
                bean.setDate(entry.getKey());
                bean.setDatelist(entry.getValue());
                System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
                list.add(bean);
            }
        }
        Collections.reverse(list);
        listnew.addAll(list);


        rlTitleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                finish();
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

                listnew.clear();
                adapter.setNewData(listnew);
                adapter.notifyDataSetChanged();
                browseDao.deleteAllRecords();
//
            }
        });

        adapter = new BaseQuickAdapter<TmExcpNewVo, BaseViewHolder>
                (R.layout.item_footprint, listnew) {

            @Override
            protected void convert(BaseViewHolder baseViewHolder, TmExcpNewVo dataBean) {
                baseViewHolder.setText(R.id.tv_date, dataBean.getDate());
                RecyclerView rv_order_goods = baseViewHolder.getView(R.id.rv_order_goods);
                Collections.reverse(dataBean.getDatelist());
                rv_order_goods.setAdapter(new BaseQuickAdapter<Browseentity, BaseViewHolder>(R.layout.item_footprint_date, dataBean.getDatelist()) {
                    @Override
                    protected void convert(@NotNull BaseViewHolder baseViewHolder, Browseentity bean) {
                        baseViewHolder.setText(R.id.tv_shop_name, bean.getCommodityname());
                        baseViewHolder.setText(R.id.tv_goods_name, bean.getShopname());
                        GlideApp.with(FootPrintActivity.this).load(IntentKey.ORDER_IMAGE + bean.getShopimg()).apply(new RequestOptions().placeholder(R.mipmap.zhanweiicon01).error(R.mipmap.zhanweiicon01)).into((ImageView) baseViewHolder.getView(R.id.img));
                        LinearLayout ll_bg = baseViewHolder.getView(R.id.ll_bg);
                        ll_bg.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                xiangqing(bean.getCommodityid()+"",bean.getShopid());


                            }
                        });

                    }


                });
            }


        };

        View emptyview = View.inflate(FootPrintActivity.this, R.layout.empty_emptylayout, null);

        adapter.setEmptyView(emptyview);
        rvOrderGoods.setAdapter(adapter);

    }
    private void xiangqing(String commodityid,String shopid) {
 EasyHttp.post(this).api(new SelectByCommodityIdApi().setId(commodityid).setUserId(SPUtil.get(this, IntentKey.USERID, ""))).request(new HttpCallback<SelectByCommodityIdBean>(this) {

        @Override
        public void onSucceed (SelectByCommodityIdBean data){
                    if (data.getCode()==0){
                        if (data.getList().getStatus() == 1) {
                            toast("商家已打样");
                        }else {
                            startActivity(new Intent(getContext(), BusinessActivity.class).putExtra("id", shopid + ""));
                        }
                    }

        }

        @Override
        public void onFail (Exception e){
            super.onFail(e);

        }
    });
}
}
